"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Separator } from "@/components/ui/separator"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle2, AlertCircle } from "lucide-react"
import { getPoll, vote, addComment, hasUserVoted } from "@/lib/db"

interface PollOption {
  id: string
  poll_id: string
  text: string
  votes: number
}

interface Comment {
  id: string
  poll_id: string
  text: string
  created_at: string
}

interface Poll {
  id: string
  title: string
  description: string
  active: boolean
  created_at: string
  options: PollOption[]
  comments: Comment[]
  poll_options?: PollOption[] // 添加这个字段以兼容不同的数据结构
}

// 客户端组件接收 id 作为 prop，而不是 params
export function PollClient({ id }: { id: string }) {
  const [poll, setPoll] = useState<Poll | null>(null)
  const [loading, setLoading] = useState(true)
  const [selectedOption, setSelectedOption] = useState<string | null>(null)
  const [comment, setComment] = useState("")
  const [submitting, setSubmitting] = useState(false)
  const [hasVoted, setHasVoted] = useState(false)
  const [voteSuccess, setVoteSuccess] = useState(false)
  const [commentSuccess, setCommentSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()

  // 直接使用传入的 id，不需要从 params 中提取
  const pollId = id

  useEffect(() => {
    const fetchPoll = async () => {
      try {
        setLoading(true)
        setError(null)

        const pollData = await getPoll(pollId)

        if (!pollData) {
          router.push("/")
          return
        }

        // 确保 poll 对象具有正确的结构
        const formattedPoll: Poll = {
          id: pollData.id,
          title: pollData.title,
          description: pollData.description,
          active: pollData.active !== false, // 默认为 true
          created_at: pollData.created_at || new Date().toISOString(),
          // 兼容不同的数据结构
          options: pollData.options || pollData.poll_options || [],
          comments: pollData.comments || [],
        }

        setPoll(formattedPoll)

        // 检查用户是否已经投票
        const voted = hasUserVoted(pollId)
        setHasVoted(voted)
      } catch (error) {
        console.error("Error fetching poll:", error)
        setError("加载投票数据失败，请稍后再试")
      } finally {
        setLoading(false)
      }
    }

    if (pollId) {
      fetchPoll()
    }
  }, [pollId, router])

  const handleVote = async () => {
    if (!selectedOption) {
      alert("请选择一个选项")
      return
    }

    setSubmitting(true)

    try {
      await vote(pollId, selectedOption)

      // 更新本地存储，标记用户已投票
      const votedPolls = JSON.parse(localStorage.getItem("votedPolls") || "[]")
      localStorage.setItem("votedPolls", JSON.stringify([...votedPolls, pollId]))

      setHasVoted(true)

      // 重新获取投票数据以更新结果
      const updatedPoll = await getPoll(pollId)
      if (updatedPoll) {
        // 确保 poll 对象具有正确的结构
        const formattedPoll: Poll = {
          id: updatedPoll.id,
          title: updatedPoll.title,
          description: updatedPoll.description,
          active: updatedPoll.active !== false, // 默认为 true
          created_at: updatedPoll.created_at || new Date().toISOString(),
          // 兼容不同的数据结构
          options: updatedPoll.options || updatedPoll.poll_options || [],
          comments: updatedPoll.comments || [],
        }

        setPoll(formattedPoll)
      }

      // 显示成功消息
      setVoteSuccess(true)
      
      // 5秒后自动返回首页
      setTimeout(() => {
        router.push("/")
      }, 5000)
    } catch (error: any) {
      console.error("Error voting:", error)
      alert(error.message || "投票失败，请稍后再试")
    } finally {
      setSubmitting(false)
    }
  }

  const handleAddComment = async () => {
    if (!comment.trim()) {
      return
    }

    setSubmitting(true)

    try {
      await addComment(pollId, comment.trim())

      setComment("")

      // 重新获取投票数据以更新评论
      const updatedPoll = await getPoll(pollId)
      if (updatedPoll) {
        // 确保 poll 对象具有正确的结构
        const formattedPoll: Poll = {
          id: updatedPoll.id,
          title: updatedPoll.title,
          description: updatedPoll.description,
          active: updatedPoll.active !== false, // 默认为 true
          created_at: updatedPoll.created_at || new Date().toISOString(),
          // 兼容不同的数据结构
          options: updatedPoll.options || updatedPoll.poll_options || [],
          comments: updatedPoll.comments || [],
        }

        setPoll(formattedPoll)
      }

      // 显示成功消息
      setCommentSuccess(true)
      setTimeout(() => setCommentSuccess(false), 3000)
    } catch (error) {
      console.error("Error commenting:", error)
      alert("评论失败，请稍后再试")
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <div className="container mx-auto px-2 sm:px-3 md:px-4 py-6 sm:py-8 md:py-10">
        <Card>
          <CardHeader>
            <Skeleton className="h-8 w-3/4" />
            <Skeleton className="h-4 w-1/2 mt-2" />
          </CardHeader>
          <CardContent className="space-y-4">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-12 w-full" />
            ))}
          </CardContent>
          <CardFooter>
            <Skeleton className="h-10 w-32" />
          </CardFooter>
        </Card>
      </div>
    )
  }

  if (error) {
    return (
      <div className="container mx-auto px-2 sm:px-3 md:px-4 py-6 sm:py-8 md:py-10">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
        <Button className="mt-4" onClick={() => router.push("/")}>
          返回首页
        </Button>
      </div>
    )
  }

  if (!poll) {
    return (
      <div className="container mx-auto px-4 py-10 text-center">
        <h1 className="text-2xl font-bold">投票不存在或已被删除</h1>
        <Button className="mt-4" onClick={() => router.push("/")}>
          返回首页
        </Button>
      </div>
    )
  }

  // 确保 options 存在
  const options = poll.options || poll.poll_options || []

  // 计算总票数
  const totalVotes = options.reduce((sum, option) => sum + (option.votes || 0), 0)

  return (
    <div className="container mx-auto px-2 sm:px-3 md:px-4 py-6 sm:py-8 md:py-10">
      <Card>
        <CardHeader>
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="text-2xl">{poll.title}</CardTitle>
              {poll.description && <CardDescription className="mt-2">{poll.description}</CardDescription>}
            </div>
            {poll.active ? <Badge className="bg-green-500">进行中</Badge> : <Badge variant="outline">已结束</Badge>}
          </div>
        </CardHeader>

        {voteSuccess && (
          <Alert className="mx-6 mb-4 bg-green-50 text-green-800 border-green-200">
            <CheckCircle2 className="h-4 w-4 text-green-600" />
            <AlertDescription>投票成功！感谢您的参与。</AlertDescription>
          </Alert>
        )}

        {commentSuccess && (
          <Alert className="mx-6 mb-4 bg-green-50 text-green-800 border-green-200">
            <CheckCircle2 className="h-4 w-4 text-green-600" />
            <AlertDescription>评论已提交！</AlertDescription>
          </Alert>
        )}

        <CardContent className="space-y-6">
          {!poll.active && (
            <div className="bg-yellow-50 p-3 rounded-md text-yellow-800 text-sm">
              此投票已结束，您可以查看结果但不能再投票
            </div>
          )}

          <div className="text-sm text-gray-500">总票数: {totalVotes}</div>

          {hasVoted || !poll.active ? (
            // 显示结果
            <div className="space-y-4">
              {options.map((option) => {
                const voteCount = option.votes || 0
                const percentage = totalVotes > 0 ? Math.round((voteCount / totalVotes) * 100) : 0

                return (
                  <div key={option.id} className="space-y-1">
                    <div className="flex justify-between items-center">
                      <span>{option.text}</span>
                      <span className="text-sm font-medium">
                        {voteCount} 票 ({percentage}%)
                      </span>
                    </div>
                    <Progress value={percentage} className="h-2" />
                  </div>
                )
              })}
            </div>
          ) : (
            // 显示投票选项
            <RadioGroup value={selectedOption || ""} onValueChange={setSelectedOption}>
              <div className="space-y-3">
                {options.map((option) => (
                  <div key={option.id} className="flex items-center space-x-2 border p-3 rounded-md">
                    <RadioGroupItem value={option.id} id={`option-${option.id}`} />
                    <Label htmlFor={`option-${option.id}`} className="flex-grow cursor-pointer">
                      {option.text}
                    </Label>
                  </div>
                ))}
              </div>
            </RadioGroup>
          )}

          <Separator className="my-4" />

          <div className="space-y-4">
            <h3 className="text-lg font-medium">匿名评论</h3>

            {poll.active && (
              <div className="space-y-2">
                <Textarea
                  placeholder="添加您的匿名评论... (可选)"
                  value={comment}
                  onChange={(e) => setComment(e.target.value)}
                  rows={3}
                />
                <Button onClick={handleAddComment} disabled={submitting || !comment.trim()}>
                  {submitting ? "提交中..." : "提交评论"}
                </Button>
              </div>
            )}

            <div className="space-y-3 mt-4">
              {poll.comments && poll.comments.length > 0 ? (
                poll.comments.map((comment) => (
                  <div key={comment.id} className="bg-muted/30 p-3 rounded-md">
                    <p>{comment.text}</p>
                    <p className="text-xs text-gray-500 mt-1">{new Date(comment.created_at).toLocaleString()}</p>
                  </div>
                ))
              ) : (
                <p className="text-gray-500 text-sm">暂无评论</p>
              )}
            </div>
          </div>
        </CardContent>
        <CardFooter className="flex justify-between">
          <Button variant="outline" onClick={() => router.push("/")}>
            返回首页
          </Button>

          {poll.active && !hasVoted && (
            <Button onClick={handleVote} disabled={submitting || !selectedOption}>
              {submitting ? "提交中..." : "提交投票"}
            </Button>
          )}
        </CardFooter>
      </Card>
    </div>
  )
}
